package com.denghq.projectbuilder.component.msgbus.sender.impl;

import com.denghq.projectbuilder.common.util.UUIDUtils;
import com.denghq.projectbuilder.component.msgbus.sender.IMsg;
import com.denghq.projectbuilder.component.msgbus.sender.IMsgSendEventHandler;
import com.denghq.projectbuilder.component.msgbus.sender.IMsgSender;
import com.denghq.projectbuilder.component.msgbus.util.RabbitMqTopicUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.Map;

@Slf4j
public class RabbitMqMsgSender implements IMsgSender {

    @Getter
    private IMsgSendEventHandler eventHandler;

    private RabbitTemplate rabbitTemplate;

    //默认发送topic到哪个交换机
    @Setter
    @Getter
    private String defaultExchange;

    //发送topic到哪个交换机
    @Setter
    @Getter
    private Map<String, String> topicExchangeMap;

    public RabbitMqMsgSender(CachingConnectionFactory connectionFactory) {
        connectionFactory.setPublisherConfirms(true);
        connectionFactory.setPublisherReturns(true);
        this.rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback((CorrelationData correlationData, boolean ack, String cause) -> {
            if (this.eventHandler != null) {
                if (ack) {
                    this.eventHandler.onSuccessEvent(new SimpleMsgSendEvent(correlationData.getId()));
                    log.info("消息发送成功:correlationData({}),ack({}),cause({})", correlationData, ack, cause);
                } else {
                    this.eventHandler.onFailEvent(new SimpleMsgSendEvent(correlationData.getId()));
                    log.info("消息发送失败:correlationData({}),ack({}),cause({})", correlationData, ack, cause);
                }
            }

        });
        rabbitTemplate.setReturnCallback((Message message, int replyCode, String replyText, String exchange_, String routingKey) -> {
            if (this.eventHandler != null) {
                this.eventHandler.onMissEvent(new SimpleMsgSendEvent(message.getMessageProperties().getCorrelationId()));
            }
            log.info("消息丢失:exchange({}),route({}),replyCode({}),replyText({}),message:{}", exchange_, routingKey, replyCode, replyText, message);
        });
    }

    @Override
    public void setSendEventHandler(IMsgSendEventHandler eventHandler) {
        this.eventHandler = eventHandler;
    }

    @Override
    public void sendMsg(String topic, IMsg msg) {
        //查找topic对应的交换机，找不到就用默认交换机
        String exchange = findExchange(topic);
        Assert.notNull(exchange, "can't find a exchange which to send. ");
        CorrelationData data = new CorrelationData();
        data.setId(msg.getMsgId() == null ? UUIDUtils.getUUID() : msg.getMsgId());
        rabbitTemplate.convertAndSend(exchange, topic, msg.getContent(), data);
    }

    private String findExchange(String topic) {
        if (!CollectionUtils.isEmpty(topicExchangeMap)) {
            for (String routingKeyExp : topicExchangeMap.keySet()) {
                if (RabbitMqTopicUtil.routingKeyMatch(routingKeyExp, topic)) {
                    return topicExchangeMap.get(routingKeyExp);
                }
            }
        }
        if (StringUtils.isNotBlank(defaultExchange)) {
            return defaultExchange;
        }

        return null;

    }

}
